package ru.compft.web.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import ru.compft.common.utils.GlobalConstants;
import ru.compft.web.WebConst;
import ru.compft.web.beans.LoginFormBean;
import ru.compft.web.utils.FacesUtils;
import ru.compft.web.view.ModuleView;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;

/**
 * User: ASUS
 * Date: 07.06.12
 * Time: 0:49
 * Контроллер страницы входа в систему
 */
@ManagedBean(name = WebConst.LOGIN_CONTROLLER)
@SessionScoped
public class LoginController implements Serializable {
    private static final long serialVersionUID = -4563511205466235147L;

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    /**
     * This action logs the user in and returns to the secure area.
     *
     * @return String path to secure area
     */
    public String loginUsingSpringAuthenticationManager() {
        // если попали сюда, значит нужно очистить все текущие модули
        final ModuleView moduleViewBean = (ModuleView) FacesUtils.getBackingBean(WebConst.MODULE_VIEW);
        if (moduleViewBean != null) {
            moduleViewBean.clearAll();
            
            if(logger.isDebugEnabled()){
                logger.debug("Cleared all current view modules from Authentication Form");
            }
        }
        //get backing bean for simple redirect form
        final LoginFormBean loginFormBean = (LoginFormBean) FacesUtils.getBackingBean(WebConst.LOGIN_FORM_BEAN);
        //authentication manager located in  Spring config: /WEB-INF/authenticationContext-security.xml
        final AuthenticationManager authenticationManager = (AuthenticationManager) FacesUtils.getSpringBean(WebConst.AUTHENTICATION_MANAGER);
        //simple token holder
        final Authentication authenticationRequestToken = createAuthenticationToken(loginFormBean);
        //authentication action
        try {
            final Authentication authenticationResponseToken = authenticationManager.authenticate(authenticationRequestToken);
            SecurityContextHolder.getContext().setAuthentication(authenticationResponseToken);
            //ok, test if authenticated, if yes reroute
            if (authenticationResponseToken.isAuthenticated()) {
                //lookup authentication success url, or find redirect parameter from login bean
                return GlobalConstants.SUCCESS;
            }
        } catch (BadCredentialsException badCredentialsException) {
            // todo сделать через файл messages
            final String msg = "Login Failed: please check your username/password and try again.";
            FacesUtils.addErrorMessage(null, msg);
        } catch (LockedException lockedException) {
            // todo сделать через файл messages
            final String msg = "Account Locked: please contact your administrator.";
            FacesUtils.addErrorMessage(null, msg);
        } catch (DisabledException disabledException) {
            // todo сделать через файл messages
            final String msg = "Account Disabled: please contact your administrator.";
            FacesUtils.addErrorMessage(null, msg);
        }

        return null;
    }

    private Authentication createAuthenticationToken(LoginFormBean loginFormBean) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(
                        loginFormBean.getUserName(),
                        loginFormBean.getPassword()
                );
        return usernamePasswordAuthenticationToken;
    }
}
